using System;
using System.Runtime;
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;



[ StructLayout( LayoutKind.Sequential , Pack = 1 ) ]
public unsafe struct SAPlayerData
{
	public int			GUID;

	public fixed byte	Name[ GameDefine.MAX_NAME ];
	
	public byte			Role;
	public byte			Color;
	public byte			RidingPet;
	public byte			WeaponType;
	
	public byte			Level;
	public byte			LevelPRO;
	public short		Unknow1;
	
	public short		HP;
	public short		MAXHP;
	public short		MP;
	public short		MAXMP;
	
	public SAMapPosMsg	Pos;
};



public class SAPlayer : MonoBehaviour
{
	private SAPlayerMove playerMove = new SAPlayerMove();
	private SACreatureAction creatureAction = null;

	[ HideInInspector ] public SACreatureData creatuerData = new SACreatureData();

	[ HideInInspector ] public int actionID = 0;

	static GameObject spriteObject = null;
	private static GameObject Create()
	{
		if ( spriteObject == null ) 
		{
			spriteObject = (GameObject)Resources.Load( "Prefabs/SAPlayer" );
			DontDestroyOnLoad( spriteObject );
		}
		
		return (GameObject)Instantiate( spriteObject );
	}
	
	public static void DestoryPlayer( GameObject obj )
	{
		Destroy( obj );

		SAPlayer player = obj.GetComponent< SAPlayer >();
		player.playerMove = null;
		player.creatureAction.clearAction();
		player.creatureAction = null;
	}

	public static GameObject CreatePlayer()
	{
		GameObject obj = Create();

		return obj;
	}



	void Start ()
	{
		//initPlayer();
	}
	

	public void initPlayer()
	{
		playerMove.owner = this;
		creatureAction = GetComponent< SACreatureAction >();

	}

	public void updateAction()
	{
		actionID = SARoleConfig.instance.getActionID( creatuerData.Role , creatuerData.Color , creatuerData.RidingPet , creatuerData.WeaponType );

		creatureAction.setActionID( actionID );
		creatureAction.playAction();
	}

	public void setDirection( int d )
	{
		creatureAction.setDirection( d );
	}

	public void setAction( int a , int d )
	{
		creatureAction.playAction( a , d );
	}

	public void movePosReal()
	{
		transform.localPosition = new Vector3( playerMove.mapPos.mapGrid.realPosX , 
		                                      playerMove.mapPos.mapGrid.realPosY ,
		                                      GameDefine.getZ( playerMove.mapPos.mapGrid.realPosY ) );
	}


	public void endMoving()
	{
		playerMove.endMoving();
	}

	public void stopMoving()
	{
		playerMove.stopMoving();
	}

	public SAMapPos getPos()
	{
		return playerMove.mapPos;
	}

	public void setPos( int x , int y )
	{
		playerMove.mapPos.mapGrid.setValue( x , y );
		movePosReal();
	}
	
	public void startMove( int x , int y )
	{
		if ( playerMove.isMoving ) 
		{
			playerMove.movePathBuffer = true;
			playerMove.movePathBackup.setValue( x , y );
			
			return;
		}

		playerMove.startMove( x , y );
	}

	public void startMove( int[] path )
	{
		playerMove.startMove( path );
	}

	void Update()
	{
		playerMove.updateMove( Time.deltaTime );
	}

}








